package com.lcm.openapi.common.models.api;

import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Getter;

/**
 * @description: 统一返回结果
 * @author: lcm
 * @date: 2021/12/13 10:58
 */

@Getter
public class Result<T> {

    public static final int SUCCESSFUL_CODE = 200;
    public static final String SUCCESSFUL_MSG = "处理成功";

    public static final int FAIL_CODE = 500;
    public static final String FAIL_MSG = "处理失败";

    private int code;

    private String msg;

    @JsonInclude(JsonInclude.Include.NON_NULL)
    private T data;

    public Result() {
    }

    public Result(IResultCode errorType) {
        this.code = errorType.getCode();
        this.msg = errorType.getMsg();
    }

    public Result(IResultCode errorType, String msg) {
        this(errorType);
        if(StrUtil.isNotEmpty(msg)){
            this.msg = msg;
        }
    }

    private Result(int code, String msg, T data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    private Result(int code , String msg, T data , int msgCode) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    public static <T> Result<T> success(T data) {
        return new Result<>(SUCCESSFUL_CODE, SUCCESSFUL_MSG, data);
    }

    public static <T> Result<T> success() {
        return success(null);
    }

    public static Result fail(IResultCode errorType) {
        return new Result<>(errorType);
    }

    public static Result fail(String msg) {
        return new Result<>(FAIL_CODE ,msg ,null);
    }

    public static Result fail(IResultCode errorType ,String msg) {
        return new Result<>(errorType ,msg);
    }

    @JsonIgnore
    public boolean isSuccess() {
        return SUCCESSFUL_CODE == this.code;
    }

    /**
     * 失败
     *
     * @return true/false
     */
    @JsonIgnore
    public boolean isFail() {
        return !isSuccess();
    }
}
